<?php
namespace app\api\controller;
use app\common\controller\Api;
use fast\Random;

/**
 * 登录模块
 */
class Login extends Api
{
    protected $noNeedLogin = ['dyLogin'];
    protected $noNeedRight = '*';

    /**
     * 抖音授权登录
     *
     * @ApiTitle    (抖音授权登录)
     * @ApiSummary  (抖音授权登录)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/login/dyLogin)
     * @ApiHeaders  (name=token, type=string, required=false, description="请求的Token")
     * @ApiParams   (name="code", type="string", required=true, description="授权code")
     * @ApiParams   (name="anonymous_code", type="string", required=true, description="anonymous_code")
     * @ApiParams   (name="nickname", type="string", required=false, description="昵称")
     * @ApiParams   (name="avatar", type="string", required=false, description="头像")
     * @ApiParams   (name="mobile", type="string", required=false, description="手机号")
     */
    public function dyLogin()
    {
        $params = $this->request->post();
        if(!$params['code']){
            $this->error('请重新授权登录', [], 201);
        }
        if(!$params['mobile']){
//            $this->error('参数错误', [], 40001);
        }
        $arr = [
            'appid'     => 'tt6a5c1ce1f56c9dd001',
            'secret'    => 'ca85a2a0fb338ada1fd6d4a8af54a6b17771b565',
            'code'      => $params['code'],
            'anonymous_code' => $params['anonymous_code'],
        ];
        // 获取授权信息
        $url = 'https://developer.toutiao.com/api/apps/v2/jscode2session';
        // 获取信息
        $res = curlPost($url,$arr,'','json');
        if($res['err_tips'] == 'success')
        {
            $openid = $res['data']['openid'];
            $unionid= $res['data']['unionid'];
            // 查询用户信息
            $user = model('app\common\model\User')->where('openid',$openid)->field('id,nickname,avatar,status')->find();
            if ($user) {
                if ($user->status != 'normal') {
                    $this->error(__('Account is locked'));
                }
                //如果已经有账号则直接登录
                $ret = $this->auth->direct($user->id);
            } else {
                $extend = [
                    'openid'    => $openid,
                    'unionid'   => $unionid,
                    'nickname'  => $params['nickname']?urldecode($params['nickname']):'',
                    'avatar'    => $params['avatar']??'',
                ];
                $username = $params['mobile'];
                if(empty($username)) {
                    $username = substr($openid,0,10);
                }
                $ret = $this->auth->register($username, Random::alnum(), '', '', $extend);
            }
            if ($ret) {
                $data = ['userinfo' => $this->auth->getUserinfo()];
                $this->success(__('Logged in successful'), $data,200);
            } else {
                $this->error($this->auth->getError());
            }
        }else{
            $this->error('登录失败',$res['error'],202);
        }
    }

}